const { Router } = require("express");
const { body, validationResult } = require("express-validator");
const doctorCtrl = require("../controllers/doctorCtrl");
const auth = require("../middleware/auth");
const multer = require('multer');
const path = require('path');

const router = new Router();

// 验证中间件
const validateRequest = (req, res, next) => {
    const result = validationResult(req);
    if (result.isEmpty()) {
        next();
    } else {
        const errors = result.array().map(err => err.msg).join(', ');
        res.json({ 
            code: 1,
            message: errors 
        });
    }
};

// 文件上传配置
const storage = multer.diskStorage({
    destination: path.join(__dirname, '../static'),
    filename: function (req, file, cb) {
        const ext = path.extname(file.originalname);
        const filename = 'doctor-avatar-' + Date.now() + ext;
        cb(null, filename);
    }
});
const upload = multer({ 
    storage: storage,
    fileFilter: (req, file, cb) => {
        // 只允许图片文件
        if (file.mimetype.startsWith('image/')) {
            cb(null, true);
        } else {
            cb(new Error('只允许上传图片文件'), false);
        }
    },
    limits: {
        fileSize: 5 * 1024 * 1024 // 5MB 限制
    }
});

// ===== 兼容性支持：保留原有路由 (放在动态路由之前) =====

/**
 * 查询全部 /api/doctor/getdoctorlist
 * GET (兼容旧版本)
 */
router.get('/getdoctorlist', auth, doctorCtrl.getdoctorlist);

/**
 * 条件联合筛选 /api/doctor/screen
 * POST (兼容旧版本)
 */
router.post('/screen', auth, doctorCtrl.getscreen);

/**
 * 根据id数组进行删除 /api/doctor/del
 * POST (兼容旧版本)
 */
router.post('/del', auth, doctorCtrl.delarr);

/**
 * 根据id编辑详情 /api/doctor/edit
 * GET (兼容旧版本)
 */
router.get('/edit', auth, doctorCtrl.edit);

/**
 * 新增 /api/doctor/add
 * POST (兼容旧版本)
 */
router.post('/add', auth, upload.single('img'), doctorCtrl.add);

/**
 * 修改 /api/doctor/change
 * POST (兼容旧版本)
 */
router.post('/change', auth, upload.single('img'), doctorCtrl.change);

// ===== 现代化 RESTful API (动态路由放在最后) =====

/**
 * 获取医生列表 /api/doctor/list
 * GET
 * Query参数: page, limit, status, Department, Courtyardarea, keyword
 */
router.get('/list', auth, doctorCtrl.getDoctors);

/**
 * 批量删除医生 /api/doctor/batch
 * DELETE
 */
router.delete('/batch', auth, doctorCtrl.batchDeleteDoctors);

/**
 * 创建医生 /api/doctor
 * POST
 */
router.post('/', [
    auth,
    upload.single('avatar'),
    body('Doctorname').notEmpty().withMessage('医生姓名不能为空'),
    body('Doctorjob').notEmpty().withMessage('职称不能为空'),
    body('Department').notEmpty().withMessage('科室不能为空'),
    validateRequest
], doctorCtrl.createDoctor);

/**
 * 获取医生详情 /api/doctor/:id
 * GET
 */
router.get('/:id', auth, doctorCtrl.getDoctorDetail);

/**
 * 更新医生 /api/doctor/:id
 * PUT
 */
router.put('/:id', [
    auth,
    upload.single('avatar')
], doctorCtrl.updateDoctor);

/**
 * 删除医生 /api/doctor/:id
 * DELETE
 */
router.delete('/:id', auth, doctorCtrl.deleteDoctor);

module.exports = router;





